Calculate Slope of a Line

Theory:

The slope of a line passing through two points (x1, y1) and (x2, y2) can be calculated using the formula:

slope = (y2 - y1) / (x2 - x1)

Python Code:

def calculate_slope(x1, y1, x2, y2):
    return (y2 - y1) / (x2 - x1)

# Taking input for coordinates and calculating slope
def calculate_and_display_slope():
    x1 = float(input("Enter the x-coordinate of the first point: "))
    y1 = float(input("Enter the y-coordinate of the first point: "))
    x2 = float(input("Enter the x-coordinate of the second point: "))
    y2 = float(input("Enter the y-coordinate of the second point: "))
    slope = calculate_slope(x1, y1, x2, y2)
    print("The slope of the line passing through the two points is:", slope)

calculate_and_display_slope()

Example Output 1:

Enter the x-coordinate of the first point: 2

Enter the y-coordinate of the first point: 3

Enter the x-coordinate of the second point: 5

Enter the y-coordinate of the second point: 7

The slope of the line passing through the two points is: 1.3333333333333333

Example Output 2:

Enter the x-coordinate of the first point: 0

Enter the y-coordinate of the first point: 0

Enter the x-coordinate of the second point: 3

Enter the y-coordinate of the second point: 4

The slope of the line passing through the two points is: 1.3333333333333333

Code Explanation:

The function calculate_slope(x1, y1, x2, y2) calculates the slope of a line passing through two points.

The function calculate_and_display_slope() takes input for the coordinates of two points, calculates the slope between them, and displays the result.